library(redist)
stopifnot(packageVersion("redist") >= "3.1.0") # need mergesplit_parallel
library(tidyverse)
library(tictoc)
library(glue)

# from get_sc_data_original
sc_shp <- read_rds('data/SC/sc_shp.rds')
sc_adj <- read_rds('data/SC/sc_adj.rds')

# set up for redist ----
sc_map_orig <- redist_map(sc_shp, existing_plan = sld_lower, pop_tol = 0.10, adj = sc_adj, total_pop = pop)
sc_map_da04 <- redist_map(sc_shp, existing_plan = sld_lower, pop_tol = 0.10, adj = sc_adj, total_pop = v4_pop)
sc_map_da12 <- redist_map(sc_shp, existing_plan = sld_lower, pop_tol = 0.10, adj = sc_adj, total_pop = v12_pop)
sc_map_da19 <- redist_map(sc_shp, existing_plan = sld_lower, pop_tol = 0.10, adj = sc_adj, total_pop = v19_pop)

# Run Mergesplit Parallel -------
#' @param .sims_per_chain number of sims per chain. Total number of sims will be
#'
#' @param .chains  number of chains to start
#'
sim_HD <- function(data, method, .sims_per_chain = 4e3, .chains = 50, map = sc_map_orig) {
    set.seed(02138)

    if (method == "HD_ms-parallel") {
        out <- redist_mergesplit_parallel(
            map = data,
            chains = .chains,
            nsims = .sims_per_chain,
            init_plan = "sample",
            counties = County,
            verbose = TRUE)
    }

    if (method == "SMC-trunc") {
        out <- redist_smc(
            map = data,
            nsims = .sims_per_chain*.chains/5,
            truncate = TRUE,
            counties = County,
            verbose = TRUE)
    }

    out
}

# subdirectory for method
dir_name <- "HD_ms-parallel"
fs::dir_create(glue("data/SC/sim/{dir_name}"))

plans_da19 <- sim_HD(sc_map_da19, method = dir_name)
write_rds(plans_da19, glue("data/SC/sim/{dir_name}/plans_da19.rds"), compress = "xz")

plans_da12 <- sim_HD(sc_map_da12, method = dir_name)
write_rds(plans_da12, glue("data/SC/sim/{dir_name}/plans_da12.rds"))

plans_orig <- sim_HD(sc_map_orig, method = dir_name)
write_rds(plans_orig, glue("data/SC/sim/{dir_name}/plans_orig.rds"))

plans_da04 <- sim_HD(sc_map_da04, method = dir_name)
write_rds(plans_da04, glue("data/SC/sim/{dir_name}/plans_da04.rds"))



# save map
write_rds(sc_map_orig, glue("data/SC/sim/{dir_name}/redist_map_orig.rds"))
